$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'jyxsjbxx/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: "id", width: 45, key: true,hidden:true },
            { label: 'userid', name: 'userid', index: "userid", width: 45,hidden:true },
            { label: '学号', name: 'xh', index: 'XH', width: 80 },
            { label: '姓名', name: 'xm', index: "xm", width: 80},
			{ label: '性别', name: 'xb', index: 'XB', width: 80,formatter: function(value, options, row){
                var str="";
                for(var i in vm.xb){
                    if(vm.xb[i].value===value){
                        str=vm.xb[i].text;
                    }
                }
                return  str;
            } },
			{ label: '身份证号', name: 'sfzh', index: 'SFZH', width: 80 }, 
			{ label: '户籍所在地', name: 'hjszd', index: 'HJSZD', width: 80 }, 
			// { label: '户籍所在地详址', name: 'hjszdxz', index: 'HJSZDXZ', width: 80 },
			// { label: '现住地址', name: 'xzdz', index: 'XZDZ', width: 80 },
			// { label: 'QQ号', name: 'qqh', index: 'QQH', width: 80 },
			// { label: '微信号', name: 'wxh', index: 'WXH', width: 80 },
			// { label: '学生头像', name: 'xstx', index: 'XSTX', width: 80 },
			// { label: '备注', name: 'bz', index: 'BZ', width: 80 },
			// { label: '操作', name: 'edit', index: 'edit', width: 80,formatter: function(value, options, row){
             //    var str = '<button class="btn" onclick="vm.userInput(\''+row.xh+'\')" >用户录入</button>';
             //    if ( row.xm != "" && row.xm != null )
             //        return "";
             //    else
             //        return  str;
            // } }
        ],
		viewrecords: true,

        height: 365,
        rowNum: 10,
		rowList : [10,30,50,100,200],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    vm.getCourseList();
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{

        },
        visableWin:false,
		showList: true,
        showUser:false,
		title: null,
        xb:[{text:'男',value:'0'},{text:'女',value:'1'}],
		jyXsjbxx: {},
        roleList:{},
        courseList:{},
        selectCoursList:[],
        xhList:[],
        nameDisabled:false,
        isEdit:false,
        user:{
            status:1,
            deptId:null,
            deptName:null,
            roleIdList:[],
            courseIdList:[],
            deptIdList:[],
        }
	},
	methods: {
        addClass:function(){
            var ids = getSelectedRows();
            var rows = $("#jqGrid").getRowData();
            if(ids == null){
                return ;
            }
            //console.log(ids);
            // console.log("=========",rows,ids);
            vm.xhList = [];
            for (var i = 0;i < rows.length;i++){
                var row = rows[i];

               for (var j = 0;j < ids.length;j++){
                   if ( ids[j] == row.id ){
                       vm.xhList.push(row.xh);
                   }
               }

            }
            vm.visableWin = true;
            vm.selectCoursList = [];

        },
        closeWin:function(){
            vm.visableWin = false;
        },
        userInput:function(xh){


            this.showUser = true;
            this.showList = false;
            vm.roleList = {};
            vm.courseList = {};
            vm.user = {deptName:null, deptId:null, status:1, roleIdList:['e7a7221f541a4ed9b37d888504ad78e4'],courseIdList:[]};
            vm.user.username = xh;
            vm.nameDisabled = true;
            //获取角色信息
            this.getRoleList();

            //获取课程信息
            this.getCourseList();

            vm.getDept();
		},
		query: function () {
			vm.reload();
		},
        sureSelectClass:function(){
            console.log(vm.selectCoursList);
            var url = "jyxskc/bathSaveByKc";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify({
                    xhs:vm.xhList.toString(),
                    kcs:vm.selectCoursList.toString()
                }),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功');
                        vm.visableWin = false;
                        //});
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
		add: function(){
            vm.isEdit = false;
			vm.showList = false;
			vm.title = "新增";
			vm.jyXsjbxx = {};
            vm.courseList = {};


            vm.user = {deptName:null, deptId:null, status:1, roleIdList:['e7a7221f541a4ed9b37d888504ad78e4'],courseIdList:[],deptIdList:[],};
            vm.nameDisabled = true;
            //获取角色信息
            this.getRoleList();

            //获取课程信息
            this.getCourseList();

            vm.getDept();
		},
		update: function (event) {
            vm.isEdit = true;
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            var userid = $("#jqGrid").getCell(id,"userid");

            vm.showList = false;
            // vm.showUser = false;
            vm.title = "修改";
            this.getRoleList();

            //获取课程信息
            this.getCourseList();

            setTimeout(function(){
                vm.getInfo(id,userid)
            },300)
		},
		saveOrUpdate: function (event) {
			var url = vm.jyXsjbxx.id == null ? "jyxsjbxx/save" : "jyxsjbxx/update";

			if ( vm.user.nickName == "" ) {
			    alert("姓名不能为空！");
			    return;
            }

            if (vm.user.password == ""){
                alert("密码不能为空！");
                return;
            }

            var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");

            if (vm.user.email == ""){
                alert("邮箱不能为空！");
                return;
            } else if(!reg.test(vm.user.email)){
                alert("邮箱格式不正确！");
                return;
            }


            if (vm.user.mobile == ""){
                alert("手机号不能为空！");
                return;
            }

			$.ajax({
				type: "POST",
			    url: baseURL + url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.jyXsjbxx),
			    success: function(r){
			    	if(r.code === 0){
						//alert('操作成功', function(index){
                            vm.user.username = vm.jyXsjbxx.xh;
                            vm.saveOrUpdate2();
						//});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
            var userid = $("#jqGrid").getCell(ids,"userid");


            confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "jyxsjbxx/delete",
				    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
                            $.ajax({
                                type: "POST",
                                url: baseURL + "sys/user/delete",
                                contentType: "application/json",
                                data: JSON.stringify([userid]),
                                success: function(r){
                                    if(r.code == 0){
                                        alert('操作成功', function(){
                                            vm.reload();
                                        });
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id,userid){
			$.get(baseURL + "jyxsjbxx/info/"+id, function(r){
                vm.jyXsjbxx = r.jyXsjbxx;
            });
            $.get(baseURL + "sys/user/info/"+userid, function(r){
                console.log(r);
                vm.user = r.user;
                vm.getDept();
                vm.user.courseIdList = new Array();
                var checkBoxValue = "" ;//已选课程的字符串
        $.ajax({
                 type: "POST",
                 url: baseURL + "jyxskc/findList",
                 datType: "JSON",
                 data: {
                 xh : vm.user.username ,
                 deleteState : "0"
                 },
                 success: function(r){
                 //                    	console.log("该学生的已选课程：");
                                    	console.log(r);
                 for(var i = 0 ; i < r.list.length ; ++i){
                 vm.user.courseIdList.push(r.list[i].kcid);
                 checkBoxValue += r.list[i].kcid ;
                 checkBoxValue += "," ;
                 }

                 setTheCheckBoxValue(checkBoxValue);
                 }
               });

            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{'name':vm.q.name}
            }).trigger("reloadGrid");
		},



        saveOrUpdate2: function () {
            var url = vm.user.userId == null ? "sys/user/save" : "sys/user/update";
//            console.log(vm.user);

//            console.log(vm.courseList);//全部课程
//        	console.log(vm.user.courseIdList);//已选课程id
            if(vm.user.userId != null){
                vm.user.password = '';
            }
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
//                        	console.log(vm.user.roleIdList);
//                        	console.log(vm.user.courseIdList);
                            //保存选课数据↓
                            var courseEditData = new Object();
                            courseEditData.xh = vm.user.username ;
                           // vm.reload();

                            $.get(baseURL + "jyxskc/bathDeleteByXh/"+courseEditData.xh, function(r){
//                                console.log(r);
//                                console.log(courseEditData.xh+"重置选课");
                            });
                          //  console.log(vm.courseList);
                            for(var i = 0 ; i < vm.courseList.length ; ++i){//遍历全部课程
                                courseEditData.kcid = vm.courseList[i].id ;
                                console.log(courseEditData.kcid);
                                if(in_array(vm.courseList[i].id ,vm.user.courseIdList)){//课程是已选课程
                                    courseEditData.deleteState = 0 ;//保存
                                    $.ajax({
                                        type: "POST",
                                        url: baseURL + "jyxskc/save",
                                        contentType: "application/json",
                                        data: JSON.stringify(courseEditData),
                                        success: function(r){
//                                        	console.log(r);
                                            if(r.code === 0){
                                                console.log("课程"+courseEditData.kcid+"状态"+courseEditData.deleteState);
                                            }else{
                                                console.log("课程保存出错");
                                            }
                                        }
                                    });
                                }

                            }
                            //保存选课数据↑
                            vm.reload2();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        getRoleList: function(){
            $.get(baseURL + "sys/role/select", function(r){
                vm.roleList = r.list;
//                console.log("vm.roleList:");
//                console.log(vm.roleList);
            });
        },
        getCourseList: function(){
            $.get(baseURL + "jykcxx/list", function(r){
                vm.courseList = r.page.list;
//                console.log(vm.courseList);
            });
        },
        getDept: function(){
            //加载部门树
            $.get(baseURL + "sys/dept/list", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r);
                var node = ztree.getNodeByParam("deptId", vm.user.deptId);
                if(node != null){
                    ztree.selectNode(node);

                    vm.user.deptName = node.name;
                }
            })
        },
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '400px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.user.deptId = node[0].deptId;
                    vm.user.deptIdList.push(node[0].deptId);
                    vm.user.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
        reload2:function(){
            vm.showUser = false;
            vm.showList = true;
            vm.reload();
        }
    }
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;

function in_array(stringToSearch, arrayToSearch) {
    for (s = 0; s < arrayToSearch.length; s++) {
        thisEntry = arrayToSearch[s].toString();
        if (thisEntry == stringToSearch) {
            return true;
        }
    }
    return false;
}

function setTheCheckBoxValue( checkBoxValue ){
    var checkBoxArray = checkBoxValue.split(",");
    for(var i=0;i<checkBoxArray.length;i++){
        $("input[name='courseCheckBox']").each(function(){
            if($(this).val()==checkBoxArray[i]){
                //$(this).attr("checked","checked");
                $(this).click();
                //console.log("checked");
            }
        })
    }
}



function fileupload(thisid) {
	//检测上传文件的类型
	if (!(/(?:xlsx|xls)$/i.test(thisid.value.toLowerCase()))) {
		Showbo.Msg.alert("只允许上传xlsx、xls格式的文件，请重新选择文件");
		return false;
		if (window.ActiveXObject) {//for IE
			thisid.select();//select the file ,and clear selection
			document.selection.clear();
		} else if (window.opera) {//for opera
			thisid.type = "text";
			thisid.type = "file";
		} else thisid.value = "";//for FF,Chrome,Safari
		return;
	} else {
		//检测上传文件的大小
		var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
		var fileSize = 0;
		if (isIE && !thisid.files) {
			var filePath = thisid.value;
			var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
			var file = fileSystem.GetFile(filePath);
			fileSize = file.Size;
		} else {
			fileSize = thisid.files[0].size;
		}
		var size = fileSize / 1024;
		if (size > (1024)) {
			Showbo.Msg.alert("文件大小不能超过1024KB，请重新选择文件");
			return false;
			if (navigator.appName.indexOf("Microsoft") != -1) {//for IE
				thisid.select();//select the file ,and clear selection
				document.selection.clear();
			} else if (window.opera) {//for opera
				thisid.type = "text";
				thisid.type = "file";
			} else {
				thisid.value = "";//for FF,Chrome,Safari
			}
			return;
		} else {
			var fd = new FormData();
			var file = document.querySelector('input[type=file]').files[0];
			fd.append('file', file);
			$.ajax({
				type: "post",
				dataType: "json",
				async: false,
				cache: false,
				url: baseURL + "jyxsjbxx/addfromexcel",
				processData: false,  // 告诉jQuery不要去处理发送的数据
				contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
				data: fd
			}).then(function (result) {
				console.log(result);
				if (result.code == 0) {
					alert("导入成功！！");
					window.location.reload();
				} else {
					alert(result.msg);
				}
			});
		}
	}
}
